<template>
  <div class="register-container">
    <div class="register-card">
      <div class="register-header">
        <h1>物业管理系统</h1>
        <h2>用户注册</h2>
      </div>
      <form @submit.prevent="handleRegister" class="register-form">
        <div class="form-group">
          <label for="name">姓名</label>
          <input
              id="name"
              v-model="formData.name"
              type="text"
              required
              placeholder="请输入真实姓名"
          >
        </div>

        <div class="form-group">
          <label for="username">用户名</label>
          <input
              id="username"
              v-model="formData.username"
              type="text"
              required
              placeholder="请设置登录用户名"
          >
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <input
              id="password"
              v-model="formData.password"
              type="password"
              required
              placeholder="请设置登录密码"
          >
        </div>

        <div class="form-group">
          <label for="contactInfo">联系电话</label>
          <input
              id="contactInfo"
              v-model="formData.contactInfo"
              type="tel"
              required
              pattern="[0-9]{11}"
              placeholder="请输入手机号码"
          >
        </div>

        <div class="form-group">
          <label for="moveInDate">入住日期</label>
          <input
              id="moveInDate"
              v-model="formData.moveInDate"
              type="date"
              required
          >
        </div>
        <div class="form-group">
          <label for="propertyId">产权证号</label>
          <select
              id="propertyId"
              v-model="formData.propertyId"
              type="number"
              required>
            <option value="">请选择您的产权证号</option>
            <option
                v-for="property in propertyList"
                :key="property.propertyCertificateNumber"
                :value="property.propertyId"
            >
              {{ property.propertyCertificateNumber }}
            </option>
          </select>
        </div>
        <div class="form-group">
          <label for="newsPreferences">新闻偏好</label>
          <select
              id="newsPreferences"
              v-model="formData.newsPreferences"
              required
          >
            <option value="">请选择您感兴趣的新闻类型</option>
            <option value="politics">政治</option>
            <option value="sports">体育</option>
            <option value="technology">科技</option>
            <option value="entertainment">娱乐</option>
            <option value="business">商业</option>
            <option value="health">健康</option>
            <option value="science">科学</option>
            <option value="education">教育</option>
          </select>
        </div>

        <div class="form-group">
          <label for="lifePreferences">生活服务偏好</label>
          <select
              id="lifePreferences"
              v-model="formData.lifePreferences"
              required
          >
            <option value="">请选择您感兴趣的生活服务类型</option>
            <option value="courier">快递代拿</option>
            <option value="caffeine">咖啡代买</option>
            <option value="milk">奶茶代拿</option>
            <option value="dog">遛狗服务</option>
            <option value="garbage">代扔垃圾</option>
            <option value="game">游戏开黑</option>
          </select>
        </div>

        <button type="submit">注 册</button>
        <div class="login-link">
          已有账号？
          <router-link to="/login">返回登录</router-link>
        </div>
        <p v-if="error" class="error-message">{{ error }}</p>
      </form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'RegisterPage',
  data() {
    return {
      formData: {
        name: '',
        username: '',
        password: '',
        contactInfo: '',
        moveInDate: '',
        propertyId: '',
        newsPreferences: '',
        lifePreferences: ''
      },
      propertyList: [],
      error: ''
    }
  },
  methods: {
    async fetchProperty() {
      try {
        const response = await fetch(`http://localhost:8080/api/properties/search/propertyCertificateNumbers`);
        if (!response.ok) throw new Error('获取产权证号信息失败');
        this.propertyList = await response.json();
      } catch (err) {
        this.error = err.message;
      }
    },

    handleRegister() {
      // 表单验证
      if (!this.formData.contactInfo.match(/^[0-9]{11}$/)) {
        this.error = '请输入正确的手机号码';
        return;
      }

      // 确保必填字段都有值
      if (!this.formData.name || !this.formData.username || !this.formData.password) {
        this.error = '请填写必填项（姓名、用户名、密码）';
        return;
      }

      // 日期格式化函数
      const formatDate = (date) => {
        const d = new Date(date);
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        return `${year}-${month}-${day} 00:00:00`;
      };

      // 构造符合后端实体类的请求数据
      const requestData = {
        name: this.formData.name.trim(),
        username: this.formData.username.trim(),
        password: this.formData.password,
        contactInfo: this.formData.contactInfo.trim(),
        moveInDate: this.formData.moveInDate ? formatDate(this.formData.moveInDate) : null,
        propertyId: parseInt(this.formData.propertyId),
        newsPreferences: this.formData.newsPreferences || null,
        lifePreferences: this.formData.lifePreferences || null
      };

      console.log('Request data:', requestData);

      // 发送注册请求
      fetch('http://localhost:8080/api/owners', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestData)
      })
          .then(response => {
            console.log('Response status:', response.status);
            if (!response.ok) {
              return response.text().then(text => Promise.reject(text));
            }
            return response.json();
          })
          .then(result => {
            console.log('Success:', result);
            alert('注册成功！');
            this.$router.push('/login');
          })
          .catch(error => {
            console.error('Error details:', error);
            this.error = '注册失败: ' + error;
          });
    }
  },
  created() {
    this.fetchProperty()
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.register-card {
  background-color: white;
  padding: 2.5rem;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 480px;
}

.register-header {
  text-align: center;
  margin-bottom: 2rem;
}

.register-header h1 {
  color: #1a1a1a;
  font-size: 1.8rem;
  margin-bottom: 0.5rem;
}

.register-header h2 {
  color: #666;
  font-size: 1.2rem;
  font-weight: normal;
}

.register-form {
  display: flex;
  flex-direction: column;
  gap: 1.2rem;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.form-group label {
  color: #4a5568;
  font-size: 0.9rem;
  font-weight: 500;
}

input, select {
  width: 100%;
  padding: 0.8rem 1rem;
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.3s ease;
}

input:focus, select:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

button {
  width: 100%;
  padding: 1rem;
  background: linear-gradient(to right, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
}

.login-link {
  text-align: center;
  margin-top: 1rem;
  color: #666;
}

.login-link a {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
}

.login-link a:hover {
  text-decoration: underline;
}

.error-message {
  color: #e53e3e;
  text-align: center;
  font-size: 0.9rem;
  margin-top: 0.5rem;
}

@media (max-width: 480px) {
  .register-card {
    padding: 1.5rem;
  }

  .register-header h1 {
    font-size: 1.5rem;
  }

  .register-header h2 {
    font-size: 1rem;
  }

  input, select {
    padding: 0.7rem;
  }

  button {
    padding: 0.8rem;
  }
}
</style> 